import { kdutils } from "kdweb-core/lib/utils"
import { KVDefine } from "../../../kds-base-define/src/KVDefine"
import { DB } from "../db"


let tableName = "t_common"
async function set(h:string,key:string,value:string) {
	await DB.redis.hset(tableName,key,value)
	return true 
}

async function get(h:string,key:string) {
	return await DB.redis.hget(tableName,key)
}

async function del(h:string,key:string) {
	return await DB.redis.hdel(tableName,key)
}

async function sett(h:string,tableName:string,key:string,value:string) {
	await DB.redis.hset(tableName,key,value)
	return true 
}

async function gett(h:string,tableName:string,key:string) {
	return await DB.redis.hget(tableName,key)
}

async function gettAll(h:string,tableName:string) {
	return await DB.redis.hgetall(tableName)
}

async function delt(h:string,tableName:string,key:string) {
	return await DB.redis.hdel(tableName,key)
}

async function removet(h:string,tableName:string) {
	return await DB.redis.del(tableName)
}


//let cTableName = "t_common_c";
//let cCacheTableName = "t_common_c_cache";
let cTableName = "new_t_common_c"
let cCacheTableName = "new_t_common_c_cache"
async function c_get(h:string,key:string,tag:string) {
	let cached = await DB.redis.hget(cCacheTableName,key)
	if(cached == tag) {
		return {
			changed:false,
			tag:tag,
		}
	}
	let data = await DB.redis.hget(cTableName,key)
	let t:KVDefine.KVChangedData = {
		changed:true,
		data:data,
		tag:cached
	}
	return t 
}

async function c_set(h:string,key:string,value:string) {
	let time = kdutils.getMillionSecond()
	await DB.redis.hset(cTableName,key,value)
	await DB.redis.hset(cCacheTableName,key,time.toString())
	return true 
}

async function c_del(h:string,key:string) {
	await DB.redis.hdel(cTableName,key)
	await DB.redis.hdel(cCacheTableName,key)
	return true 
}

export let RpcKV = {
	set,
	get,
	del,

	sett,
	gett,
	gettAll,
	delt,
	removet,
	cleart:removet,
}

export let RpcChangedKV = {
	set:c_set,
	get:c_get,
	del:c_del
}
let db = DB.get("tds-kv")
async function m_insert(h:string,tableName:string,data:any) {
	return await db.insert(tableName,data)
}

async function m_get(h:string,tableName:string,index:any) {
	return await db.get(tableName,index)
}

async function m_update(h:string,tableName:string,index:any,data:any) {
	return await db.update(tableName,index,data)
}

async function m_delete(h:string,tableName:string,index:any) {
	return await db.delMany(tableName,index)
}

export let RpcMongoKV = {
	insert:m_insert,
	get:m_get,
	update:m_update,
	delete:m_delete,
}